require "core"

class User < ActiveRecord::Base
  include LockDown::Core::UserGroups
  
  has_one :updater

  belongs_to :role

  has_and_belongs_to_many :user_groups
  has_and_belongs_to_many :editor_groups
  validates_presence_of :login

  validates_uniqueness_of :login 

  validates_confirmation_of :password 
 
  after_validation :prepare_for_save
  
  #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  # Class methods
  #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  
  class << self
    def authenticate(login,pass)
      find(:first, :conditions => ["login = ? and password = ?", login, LockDown::Encryption.encrypt(pass)])
    end

    def find_by_sid(sid)
      r = find(:first, :conditions => ["sid = ?",sid])
      return r if r.nil?
      if r.reset_request_at < (Time.now - LockDown::PASSWORD_RESET_TIMEOUT)
        r.sid = nil
        r.reset_request_at = nil
        r.save
        return nil
      end
      return r
    end
  end #end class methods

  def encrypt_password
    pass = self.password.dup
    self.password = LockDown::Encryption.encrypt(pass)
    self.password_confirmation = LockDown::Encryption.encrypt(pass)
  end
  
  private
    def prepare_for_save
      if self.password && self.password_confirmation
        self.encrypt_password
      end
    end
end
